package com.niuniu.rushdorm.service.impl;


import com.niuniu.rushdorm.exception.ReportedException;
import com.niuniu.rushdorm.mapper.GroupsMapper;
import com.niuniu.rushdorm.mapper.GroupsUserMapper;
import com.niuniu.rushdorm.mapper.StudentMapper;
import com.niuniu.rushdorm.mapper.UserMapper;
import com.niuniu.rushdorm.pojo.entity.Groups;
import com.niuniu.rushdorm.pojo.entity.GroupsUser;

import com.niuniu.rushdorm.pojo.entity.Student;
import com.niuniu.rushdorm.pojo.vo.UserVO;
import com.niuniu.rushdorm.pojo.vo.ResultVO;
import com.niuniu.rushdorm.service.GroupsService;

import com.niuniu.rushdorm.util.StatusEnum;
import com.niuniu.rushdorm.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GroupsServiceImpl implements GroupsService {
    @Autowired
    private GroupsMapper groupsMapper;
    @Autowired
    private GroupsUserMapper groupsUserMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public ResultVO create(String groupName, String desc, long uid) {
        //判断队名是否为空
        if (StringUtils.isBlank(groupName))
        {
            throw ReportedException.build(StatusEnum.GROUP_EMPTY_FORM);
        }
        //如果描述为空,则用队名作为描述
        if (desc == null)
        {
            desc = groupName;
        }

        //判断用户是否已经组队
        if (groupsUserMapper.selectByUid(uid) != null)
        {
            throw ReportedException.build(StatusEnum.GROUP_ALREADY_HAVE_TEAM);
        }

        //生成邀请码
        String inviteCode = UUIDUtils.uuid();

        //插入队伍表
        Groups groups = new Groups();
        groups.setName(groupName);
        groups.setDescribe(desc);
        groups.setInviteCode(inviteCode);
        groupsMapper.insert(groups);


        //插入成员表
        int joinTime = (int)(System.currentTimeMillis() / 1000);//获取当前时间的秒值
        GroupsUser groupsUser = new GroupsUser();
        groupsUser.setGroupId(groups.getId());
        groupsUser.setIsCreator(1);
        groupsUser.setUid(uid);
        groupsUser.setJoinTime(joinTime);
        groupsUserMapper.insert(groupsUser);

        //装配返回结果集
        Map<String, String> resMap = new HashMap<>();
        resMap.put("team_id", groups.getId().toString());
        resMap.put("invite_code", inviteCode);
        return ResultVO.success(resMap);
    }

    @Override
    public ResultVO delete(long uid) {
        //判断是否有该队伍
        GroupsUser groupsUser = groupsUserMapper.selectByUid(uid);
        if (groupsUser == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_NO_SUCH_GROUP);
        }

       Integer teamId = groupsUser.getGroupId();
        Groups group = groupsMapper.selectById(teamId);

        //队伍是否已经分配了宿舍
        if (group.getStatus() == 1)
        {
            throw ReportedException.build(StatusEnum.GROUP_ALREADY_ALLOCATED);
        }

        //判断队伍成员数是否大于1
        if (groupsUserMapper.selectMembers(teamId) > 1)
        {
            throw ReportedException.build(StatusEnum.GROUP_HAVE_MEMBERS);
        }

        //判断操作人是否是队伍创建人
        if (groupsUser.getIsCreator() == 0)
        {
            throw ReportedException.build(StatusEnum.GROUP_NO_AUTHORITY);
        }

        //更改队伍表和成员表
        groupsMapper.deleteGroup(teamId);

        groupsUserMapper.deleteGroup(teamId);

        return ResultVO.success(null);

    }

    @Override
    public ResultVO join(long uid,int gender, String inviteCode) {
        //判断是否已经加入组
        if (groupsUserMapper.selectByUid(uid) != null)
        {
                throw ReportedException.build(StatusEnum.GROUP_ALREADY_JOINED);
        }
        //判断邀请码是否正确
        Groups group = groupsMapper.selectByInviteCode(inviteCode);
        if (group == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_NO_SUCH_GROUP);

        }
        //判断队伍是否分配完宿舍
        if (group.getStatus() == 1)
        {
            throw ReportedException.build(StatusEnum.GROUP_ALREADY_ALLOCATED);
        }

        //判断队伍人数是否超过上限
        int groupLimit = 4;
        if (groupsUserMapper.selectMembers(group.getId()) >= groupLimit)
        {
            throw ReportedException.build(StatusEnum.GROUP_REACH_GROUP_LIMIT);
        }
        //判断队伍性别是否一致
        long creatorUid = groupsUserMapper.getCreatorUid(group.getId());
        UserVO creatorUser = userMapper.getUser(creatorUid);
        if (creatorUser.getGender() != gender)
        {
            throw ReportedException.build(StatusEnum.GROUP_GENDER_UNMATCHED);
        }

        //插入队伍成员表
        int joinTime = (int)(System.currentTimeMillis() / 1000);//获取当前时间的秒值
        GroupsUser groupsUser = new GroupsUser();
        groupsUser.setGroupId(group.getId());
        groupsUser.setIsCreator(0);
        groupsUser.setUid(uid);
        groupsUser.setJoinTime(joinTime);
        groupsUserMapper.insert(groupsUser);

        //返回结果集
        Map<String, Integer> resMap = new HashMap<>();
        resMap.put("team_id", group.getId());
        return ResultVO.success(resMap);
    }

    @Override
    public ResultVO leave(long uid) {

        //判断是否加入组
        GroupsUser groupsUser = groupsUserMapper.selectByUid(uid);
        if (groupsUser == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_NOT_EXIST);
        }
        //判断是否为创建人
        if (groupsUser.getIsCreator() == 1)
        {
            throw ReportedException.build(StatusEnum.GROUP_CREATOR_CAN_NOT_LEAVE);
        }
        //判断队伍是否分配完毕
        Groups group = groupsMapper.selectById(groupsUser.getGroupId());
        if (group.getStatus() == 1)
        {
            throw ReportedException.build(StatusEnum.GROUP_ALREADY_ALLOCATED);
        }

        //修改队伍成员表
        int leaveTime = (int)(System.currentTimeMillis() / 1000);
        groupsUser.setLeaveTime(leaveTime);
        groupsUserMapper.leaveGroup(groupsUser);

        //返回结果集

        return ResultVO.success(null);



    }

    @Override
    public ResultVO my(long uid) {
        //判断是否组队
        GroupsUser groupsUser = groupsUserMapper.selectByUid(uid);

        if (groupsUser == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_NOT_EXIST);
        }

        //获取组及组员信息
        int groupId = groupsUser.getGroupId();
        Groups group = groupsMapper.selectById(groupId);
        List<Long> uidList = groupsUserMapper.selectByGroupId(groupId);
        List<Student> memberList = studentMapper.getStudentByUids(uidList);

        //封装返回结果

        Map<String, Object> resultMap = new HashMap<>();
        List<Object> members = new ArrayList<>();
        resultMap.put("group_id", groupId);
        resultMap.put("group_name", group.getName());
        resultMap.put("invite_code", group.getInviteCode());
        for(Student stu : memberList)
        {
            Map<String, String> stuInfo = new HashMap<>();
            stuInfo.put("student_id", stu.getStudentId());
            stuInfo.put("student_name", userMapper.getUserName(stu.getUid()));
            members.add(stuInfo);
        }
        resultMap.put("members", members);
        return ResultVO.success(resultMap);


    }

    @Override
    public ResultVO transfer(long uid, String studentId) {
        //判断学号是否正确
        Long newCreatorUid = studentMapper.getUidByStudentId(studentId);
        if (newCreatorUid == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_WRONG_FORMAT);
        }
        //判断是否加入队伍
        GroupsUser groupsUserLeader = groupsUserMapper.selectByUid(uid);
        if (groupsUserLeader == null)
        {
            throw ReportedException.build(StatusEnum.GROUP_NOT_EXIST);
        }

        //判断是否是创建人
        if (groupsUserLeader.getIsCreator() == 0)
        {
            throw ReportedException.build(StatusEnum.GROUP_NO_AUTHORITY);
        }
        //判断被转交人是否是组员
        GroupsUser groupsUserMem = groupsUserMapper.selectByUid(newCreatorUid);
        if (groupsUserMem == null || groupsUserMem.getGroupId() != groupsUserLeader.getGroupId())
        {
            throw ReportedException.build(StatusEnum.GROUP_NOT_MEMBERS);
        }

        //修改组员表
        groupsUserMem.setIsCreator(1);
        groupsUserLeader.setIsCreator(0);

        groupsUserMapper.setCreator(groupsUserLeader);
        groupsUserMapper.setCreator(groupsUserMem);




        return ResultVO.success(null);
    }
}
